package cc.laop.netty.client;

import java.util.UUID;

import cc.laop.netty.entity.LoginMsg;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.timeout.IdleStateHandler;

public class NettyClient {

    private SocketChannel socketChannel;

    public void start(String ip, int port) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap boot = new Bootstrap();
        boot.channel(NioSocketChannel.class);
        boot.group(group);
        boot.remoteAddress(ip, port);
        boot.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel)
                    throws Exception {
                socketChannel.pipeline()
                        .addLast(new IdleStateHandler(0, 0, 10));
                socketChannel.pipeline().addLast(new ObjectEncoder());
                socketChannel.pipeline().addLast(
                        new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
                socketChannel.pipeline().addLast(new NettyClientHandler());
            }
        });

        ChannelFuture future = boot.connect(ip, port).sync();
        if (future.isSuccess()) {
            socketChannel = (SocketChannel) future.channel();
            System.out.println(
                    Thread.currentThread().getName() + ": connect server.");
        }
    }

    public static void main(String[] args) {
        group(200);
    }

    public static void group(int thread) {
        for (int i = 0; i < thread; i++) {
            final int j = i;
            Thread t = new Thread() {
                public void run() {
                    NettyClient nc = new NettyClient();
                    try {
                        nc.start("192.168.1.250", 9100);
                        String channelid = UUID.randomUUID().toString();
                        Constants.channelid.set(channelid);
                        LoginMsg lm = new LoginMsg();
                        lm.setChannelid(channelid);
                        lm.setUserid(String.valueOf(j));
                        nc.socketChannel.writeAndFlush(lm);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                ;
            };
            t.start();
        }
    }

}
